package com.example.wearing;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class LoginActivity extends AppCompatActivity implements Runnable{

    /*判断sharedpreference中是否有用户数据
	    有——直接进去主页
        无——登录——保存至sharedpreference——进入
    */

    private static final String TAG = "LoginActivity";
    EditText name, pwd;
    Button loginBtn, redisBtn;
    String userName, userPwd;
    String jdbcUrl, jdbcUser, jdbcPassword;

    private Handler handler;

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        name = findViewById(R.id.name);
        pwd = findViewById(R.id.pwd);

        //将jdbc连接数据库参数放入sharedPreference中
        SharedPreferences sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("base_level", 0); //根据用户自身情况，进行穿衣等级的调整
        editor.putInt("feedback_num", 0); //反馈次数
        editor.putString("jdbc_url", "jdbc:mysql://192.168.0.105:3306/wearingdb?autoReconnect=true");
        editor.putString("jdbc_user", "root");
        editor.putString("jdbc_password", "root");
        editor.apply();

        //检查sharedPreference
        PreferenceManager.getDefaultSharedPreferences(this);
        //获取数据
        userName = sp.getString("user_name","");
        userPwd = sp.getString("user_pwd","");
        String userName = sp.getString("user_name","");
        String userCity = sp.getString("user_city","");
        String userImg = sp.getString("user_img","");
        jdbcUrl = sp.getString("jdbc_url", "");
        jdbcUser = sp.getString("jdbc_user","");
        jdbcPassword = sp.getString("jdbc_password","");

        if(userName.equals("")||userPwd.equals("")){
            //说明之前未登录，没有信息

            //点击登录按钮
            loginBtn = findViewById(R.id.loginBtn);
            loginBtn.setOnClickListener(new View.OnClickListener() {
                @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
                @Override
                public void onClick(View view) {
                    login();
                }
            });

            //点击注册按钮
            redisBtn = findViewById(R.id.regisBtn);
            redisBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent register = new Intent(LoginActivity.this,RegisterActivity.class);
                    startActivity(register);
                }
            });
        }else{
            //已有信息，直接进去主页面
            Intent loginIntent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(loginIntent);
            finish();
        }

    }

    //账号密码登录
    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    private void login() {
        userName = name.getText().toString().trim();
        userPwd = pwd.getText().toString().trim();

        //判断是否有空值
        if(userName.isEmpty()){
            Toast.makeText(getApplicationContext(), "请输入用户名", Toast.LENGTH_LONG).show();
            return;
        }
        if(userPwd.isEmpty()){
            Toast.makeText(getApplicationContext(), "请输入密码", Toast.LENGTH_LONG).show();
            return;
        }
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg){
                Log.i(TAG, "handleMessage: 收到消息");

                if(msg.what==1){
                    //接收消息
                    int res = (int) msg.obj;
                    if(res == 1){
                        //密码错误
                        Toast.makeText(getApplicationContext(), "登录失败：密码错误" , Toast.LENGTH_SHORT).show();
                    }else if(res == 2){
                        //登录成功
                        Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
                        //进入主页面
                        Intent loginIntent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(loginIntent);
                    }else if(res == 3){
                        //用户不存在
                        Toast.makeText(getApplicationContext(), "登录失败：该用户不存在，请先注册再登录", Toast.LENGTH_SHORT).show();
                    }
                }
                super.handleMessage(msg);
            }
        };

        //开启线程，判断是否用户是否存在、密码是否正确
        Thread thread = new Thread(this);
        thread.start();

    }


    //创建线程类，实现Runnable接口，用于查询用户数据
    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void run() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection cn = DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPassword);
            String sql = "select * from user where u_name='"+userName+"';";
            Statement st = (Statement)cn.createStatement();
            ResultSet rs = st.executeQuery(sql);

            System.out.println("连接数据库成功");

            rs.last(); // 将光标移动到最后一行
            int rowCount = rs.getRow(); // 得到当前行号，即结果集记录数
            Log.i(TAG, "run: rowcount:"+rowCount);
            rs.beforeFirst();//将光标移回首行
            rs.next();

            int resCode = 0;//标识3种情况，密码错误、登录成功、用户不存在

            if(rowCount == 1){
                //只有一条记录
                String pwdTemp = rs.getString("u_pwd");
                //判断密码是否匹配
                if(!userPwd.equals(pwdTemp)){
                    //密码错误
                    resCode = 1;
                }else{
                    //符合条件
                    resCode = 2;
                    Log.i(TAG, "done: 登录成功");
                    //将数据存放到SharedPreferences中
                    SharedPreferences sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putInt("user_id", rs.getInt("u_id"));
                    editor.putString("user_pwd", userPwd);
                    editor.putString("user_name", userName);
                    editor.putString("user_city", rs.getString("u_city"));
                    editor.putString("user_img",rs.getString("u_img"));
                    editor.apply();
                    Log.i(TAG, "done: name:"+userName);
                }
            }else if(rowCount == 0){
                //用户不存在
                resCode = 3;
            }

            //发送消息
            Message msg = handler.obtainMessage(1, resCode);
            handler.sendMessage(msg);
            Log.i(TAG, "run: 消息已发送---查询结果");

            rs.close();
            st.close();
            cn.close();
        } catch (ClassNotFoundException e) {
            Log.i(TAG, "run:SQL fail!!!__"+e);
            e.printStackTrace();
        } catch (SQLException e) {
            Log.i(TAG, "run:SQL fail!!!__"+e);
            e.printStackTrace();
        }
    }

}